package com.cwt_taxi_xa.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.protocol.DispatchCenterUsers;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.Tools;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class DvrTCService extends Service {

	public static boolean isconnect_zg = false;//郑工dvr是否连接


	Socket socket;
	boolean reading = false;
	InputStream ist;
	OutputStream ost;
	int size;
	byte[] buffer = new byte[1024];

	private static DvrTCService instance;

	public static DvrTCService getInstance() {
		return instance;
	}

	public void dvrTC(byte[] data){
		try {
			ost.write(data);
			AppLog.e("透传平台指令到dvr："+Tools.parseByte2HexStr(data));
		} catch (Exception e) {
			AppLog.e("透传平台指令到dvr失败，重连后再传");
			isconnect_zg = false;
			connectDVR(data);
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		instance = this;

		connectDVR(null);
		startRead();

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		reading = false;
		closeDVR();
	}


	void connectDVR(final byte[] data) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					AppLog.e("连接dvr视频透传通道");
					socket = new Socket(SPConstants.SPV_dvrip_zg, 6691);
					ist = socket.getInputStream();
					ost = socket.getOutputStream();
					AppLog.e("连接dvr视频透传通道--成功");
					isconnect_zg = true;

					if(data!=null){
						ost.write(data);
						AppLog.e("连接dvr视频透传通道--成功--补传指令："+Tools.parseByte2HexStr(data));
					}
				} catch (Exception e) {
//					e.printStackTrace();
					AppLog.e("连接dvr视频透传通道--失败");
				}
			}
		}).start();
	}

	void closeDVR() {
		try {
			if(ist!=null){
				ist.close();
				ist = null;
			}
			if(ost!=null){
				ost.close();
				ost = null;
			}
			if(socket!=null){
				socket.close();
				socket = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	void startRead(){
		reading = true;
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (reading) {
					try {
						if(socket!=null&&ist!=null&&ist.available()>0){
							size = ist.read(buffer);
//							AppLog.e("-------------------------reading:" + size);
							if (size > 0) {
								AppLog.e("透传dvr应答到平台："+Tools.parseByte2HexStr(Tools.byteTobyte(buffer, 0, size)));
								DispatchCenterUsers.witeMsg(Tools.byteTobyte(buffer, 0, size));
//								AppLog.e(size + "------" + Tools.parseByte2HexStr(Tools.byteTobyte(buffer, 0, size)));
							}
						}else{
							Thread.sleep(200);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}











}
